<template>
  <div class="order-management">
    <!-- 搜索栏 -->
    <div class="search-bar">
    <div>
      <el-input
        v-model="orderNum"
        placeholder="请输入订单号"
        style="width: 200px; margin-left: 20px;"
      />
    </div>
    <div style="margin-right: 20px">
      <el-button type="primary" @click="searchOrders" style="margin-left: 10px">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>
    </div>

    <!-- 订单列表v-for="item in scope.goods" :key="item.goodId"  -->
    <el-table :data="pageOrderList" border class="order-table">
      <el-table-column prop="orderNum" label="订单号" width="180" />
      <el-table-column label="商品信息" min-width="300">
        <template #default="scope">
          <div class="order-item">
            <el-image
              :src="scope.row.goods.images"
              style="width: 50px; height: 50px"
            />
            <div class="item-info">
              <div>{{ scope.row.goods.goodName }}</div>
              <div class="item-spec">{{ scope.row.goods.description }}</div>
              <div class="item-price">
                ¥{{ scope.row.goods.price }} x {{ scope.row.amount }}
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="收货信息" width="200">
        <template #default="scope">
          <div>{{ scope.row.buyer.username }}</div>
          <div class="address-text">{{ scope.row.logistics }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="totalAmount" label="订单金额" width="120">
        <template #default="scope">
          ¥{{ scope.row.payment }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="下单时间" width="180" />
      <el-table-column prop="status" label="订单状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small"
            @click="viewOrderDetail(scope.row)"
          >
            详情
          </el-button>
          <el-button 
            v-if="scope.row.status == 1"
            type="success" 
            size="small"
            @click="showDeliveryDialog(scope.row)"
          >
            发货
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[5]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
    >
      <div class="order-detail" v-if="currentOrder">
        <div class="detail-section">
          <h4>订单信息</h4>
          <div class="detail-item">
            <span>订单号：</span>
            <span>{{ currentOrder.orderNum }}</span>
          </div>
          <div class="detail-item">
            <span>下单时间：</span>
            <span>{{ currentOrder.createTime }}</span>
          </div>
          <div class="detail-item">
            <span>订单状态：</span>
            <span>{{ getStatusText(currentOrder.status) }}</span>
          </div>
        </div>

        <div class="detail-section">
          <h4>收货信息</h4>
          <div class="detail-item">
            <span>收货人：</span>
            <span>{{ currentOrder.buyer.username }}</span>
          </div>
          <div class="detail-item">
            <span>联系电话：</span>
            <span>{{ currentOrder.buyer.phone }}</span>
          </div>
          <div class="detail-item">
            <span>收货地址：</span>
            <span>{{ currentOrder.logistics }}</span>
          </div>
        </div>
        <div class="detail-section">
          <h4>商品信息</h4>
          <el-table :data="getItemsArray(currentOrder.goods,currentOrder.remark,currentOrder.payment,currentOrder.amount)" border>
            <el-table-column label="商品图片" width="100">
              <template #default="scope">
                <el-image
                  :src="scope.row.images"
                  style="width: 50px; height: 50px"
                />
              </template>
            </el-table-column>
            <el-table-column prop="goodName" label="商品名称" />
            <el-table-column prop="remark" label="规格" width="150" />
            <el-table-column prop="price" label="单价" width="100">
              <template #default="scope">
                ¥{{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="数量" width="80" />
            <el-table-column prop="payment" label="支付" width="100" />
          </el-table>
          <div class="order-total">
            总计：¥{{ currentOrder.payment }}
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { getPurchaseListAPI,updatePurchaseAPI } from '@/api/store'
import { getUserInfoApi } from '@/api/user'
import { useTokenStore } from '@/store/token';

// 用户信息
const tokenStore = useTokenStore()
const factory = tokenStore.factory;

// 搜索表单
const orderNum = ref('')

const orderList = ref([
  {
    purchaseId: '',
    orderNum: '',
    amount: '',
    price: '',
    payment: '',
    createTime: '',
    payTime: '',
    goods: {
      goodId: '',
      goodName: '',
      price: '',
      description: '',
      images: '',
      status: '',
      isOnShelf: '',
      style: {
        styleId: '',
        categoryId: '',
        styleName: '',
        category: {
          categoryName: ''
        }
      }
    },
    factory: {
      factoryId: '',
    },
    user: {
      userId: '',
      username: '',
      phone: ''
    },
    remark: ''
  }
])
// 获取订单列表
const pageOrderList = ref([]); // 当前页的数据（用于显示）
// const orderList = ref([])
function getOrderList() {
  const factoryId = factory.factoryId
  console.log(factoryId);
  getPurchaseListAPI({
    sellerId: tokenStore.user.userId,
    sellerType: "加工厂"
  }).then(res => {
    orderList.value = res.data
    total.value = orderList.value.length
    pagePages.value = Math.ceil(total.value / pageSize.value); // 计算总页数
    updatePaginatedList();   // 更新分页数据
  })
}
getOrderList();

// 当前查看的订单
const currentOrder = ref(null)
const detailDialogVisible = ref(false)

// 搜索订单
const searchOrders = () => {
  // 调用接口搜索订单
  console.log(orderNum.value);
  
  getPurchaseListAPI({
    sellerId: tokenStore.user.userId,
    sellerType: "加工厂",
    orderNum: orderNum.value
  }).then(res => {
    orderList.value = res.data
    total.value = orderList.value.length
    pagePages.value = Math.ceil(total.value / pageSize.value); // 计算总页数
    updatePaginatedList();   // 更新分页数据
  })
}

const resetSearch = () => {
  orderNum.value = ''
  getOrderList();
}

//分页
const total = ref(0); // 总条数
const pagePages = ref(1); // 总页数
const currentPage = ref(1); // 当前页码
const pageSize = ref(5);  // 每页显示条数

// 更新分页数据（根据 currentPage 和 pageSize）
const updatePaginatedList = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  pageOrderList.value = orderList.value.slice(start, end);  // 切割出当前页的数据
};

// 处理每页条数变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize; // 更新每页显示的条目数
  updatePaginatedList();  // 更新分页数据
};

// 处理当前页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage; // 更新当前页码
  updatePaginatedList();  // 更新分页数据
};

// 订单状态处理
const getStatusType = (status) => {
  const statusMap = {
    0: 'warning',   // 待付款
    1: 'primary',   // 待发货
    2: 'success',   // 待收货
    3: 'info',      // 已完成
    4: 'danger'     // 已取消
  }
  return statusMap[status]
}

const getStatusText = (status) => {
  const statusMap = {
    0: '待付款',
    1: '待发货',
    2: '待收货',
    3: '已完成',
    4: '已取消'
  }
  return statusMap[status]
}

// 查看订单详情
const viewOrderDetail = (order) => {
  currentOrder.value = order
  const userId = currentOrder.value.userId
  getUserInfoApi(userId).then(res=>{
    console.log(res);
    currentOrder.value.user = res.data[0]
  })
  
  detailDialogVisible.value = true
}

// 获取商品数组
function getItemsArray(goods, remark, payment, amount) {
  const items = [goods]
  return items.map(item => ({
    ...item,        // 解构商品对象，保留原有字段
    remark,         // 将 remark 添加到每个商品对象
    payment,        // 将 payment 添加到每个商品对象
    amount          // 将 amount 添加到每个商品对象
  }));
}

// 发货处理
const showDeliveryDialog = (order) => {
  currentOrder.value = order
  const purchaseId = currentOrder.value.purchaseId
  const status = ref(2)
  let data = {
    purchaseId: purchaseId,
    status: status.value
  }
  updatePurchaseAPI(data).then(res => {
    if (res.code === 0) {
      ElMessage.success('发货成功!')
    } else {
      ElMessage.error(res.message)
    }
    getOrderList()
  })
}

</script>

<style scoped>
.order-management {
  padding: 20px;
  position: relative;

}

.search-bar {
  display: flex;
  align-items: center;
  background: #fff;
  height: 80px;
}

.order-table{
  margin-top: 20px;
  max-height: 100vh ;
  width: 100%;
}

.pagination {
  position: absolute;
  margin-top: 20px;
  margin-left: 20%;
  display: flex;
  justify-content: flex-end;
}

.order-item {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.order-item:last-child {
  border-bottom: none;
}

.item-info {
  margin-left: 10px;
  flex: 1;
}

.item-spec {
  color: #999;
  font-size: 12px;
  margin: 5px 0;
}

.item-price {
  color: #666;
}

.address-text {
  color: #666;
  word-break: break-all;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h4 {
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
}

.detail-item span:first-child {
  width: 100px;
  color: #666;
}

.order-total {
  text-align: right;
  margin-top: 10px;
  font-weight: bold;
}
</style>